package com.entor.fiter;

import com.entor.util.ErrorCode;
import com.entor.util.JWTUtils;
import com.entor.util.PrintUtil;
import com.entor.util.Result;
import lombok.SneakyThrows;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String s = request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
        if(s.contains("login")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Authorization");
        if(token==null||token.equals("")){
            PrintUtil.print(response, ErrorCode.USERNAME_IS_NULL);
        }
        Result result = JWTUtils.checkToken(token);
        //认证不通过
        if(result.getCode()!=0){
            PrintUtil.print(response, ErrorCode.USERNAME_IS_NULL);
        }
        //获取token的用户信息
        Map<String,Object> data = (Map<String, Object>) result.getData();
        String  username = (String) data.get("username");
    }

    @Override
    public void destroy() {

    }
}
